package sshclient

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"strings"

	"golang.org/x/crypto/ssh"
)

//  sshDial - 连接到SSH服务器
func SSHDial(hostname string, port string, username string, password string) (*ssh.Client, error) {
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{ssh.Password(password)},
		HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
			return nil
		},
	}

	log.Println("[INFO]", "Connecting to", hostname, port)
	hostAddress := strings.Join([]string{hostname, port}, ":")
	client, err := ssh.Dial("tcp", hostAddress, config)
	if err != nil {
		log.Println("[ERROR] ", err.Error())
		return client, err
	}

	return client, err
}

// runCMD - 执行
func RunCMD(client *ssh.Client, cmdString string) (rtnString string) {
	session, err := client.NewSession()
	if err != nil {
		log.Panicln("[ERROR] ", err.Error())
	}
	defer session.Close()

	var buff bytes.Buffer
	session.Stdout = &buff
	if err := session.Run(cmdString); err != nil {
		fmt.Println(err.Error())
	}

	return buff.String()
}
